import Base from "./Base"
import Rect from "./Rect"
import { V2Util } from "../util/V2Util"

const v2 = V2Util;

/** 圆形参数接口 */
export interface ICircle {
    x?: number,
    y?: number,
    w?: number,
    ang?: number
}

/** 圆形类 */
export default class Circle extends Base {

    /** 半径 */
    get r() { return this.w * 0.5 }
    set r(r: number) { this.w = r * 2 }

    constructor(obj?: ICircle) {
        super(obj)
    }

    /** 复制 */
    cp(): Circle {
        return new Circle(this)
    }

    /** 判断是否与目标碰撞 */
    collide(obj: Base) {
        return obj instanceof Circle ? Circle.collideCircle(this, obj) :
            obj instanceof Rect ? Circle.collideRect(this, obj) : false
    }

    /** 判断是否被目标包含 */
    in(obj: Base) {
        return obj instanceof Circle ? Circle.inCircle(this, obj) :
            obj instanceof Rect ? Circle.inRect(this, obj) : false
    }

    /** 判断圆形是否碰撞到目标圆形 */
    static collideCircle(c1: Circle, c2: Circle) {
        return c1.dis(c2) < c1.r + c2.r
    }

    /** 判断圆形是否碰撞到目标矩形 */
    static collideRect(circle: Circle, rect: Rect) {
        let cr = circle.r
        let rw_2 = rect.w * 0.5
        let rh_2 = rect.h * 0.5
        //计算圆形到矩形中心的xy距离
        let dx = Math.abs(circle.x - rect.x)
        let dy = Math.abs(circle.y - rect.y)
        //检测碰到边
        if (dx > cr + rw_2 || dy > cr + rh_2) return false
        if (dx < rw_2 || dy < rh_2) return true
        //检测碰到顶点
        if (v2.dis(v2.toFirstQuad(circle, rect), rect.getVertex(0)) < cr) return true
        return false
    }

    /** 判断圆1是否被圆2包含 */
    static inCircle(c1: Circle, c2: Circle) {
        return c1.dis(c2) < c2.r - c1.r
    }

    /** 判断圆形是否被矩形包含 */
    static inRect(circle: Circle, rect: Rect) {
        //圆在矩形第一象限的右上xy小于矩形第一象限顶点的xy则为被包含
        let pos = v2.toFirstQuad(circle, rect)
        let rv = rect.getVertex(0)
        let cr = circle.r
        return pos.x + cr < rv.x && pos.y + cr < rv.y
    }
}
